package com.common.des;

import java.security.Key;
import java.security.SecureRandom;

import javax.crypto.Cipher;
import javax.crypto.KeyGenerator;

import org.apache.commons.codec.binary.Base64;

public class DESUtils {
	private static Key key;// DES加密解密所用的秘钥
	private static String KEY_STR = "myKey";

	static {
		try {
			KeyGenerator generator = KeyGenerator.getInstance("DES");
			generator.init(new SecureRandom(KEY_STR.getBytes()));
			key = generator.generateKey();
			generator = null;
		} catch (Exception e) {
			throw new RuntimeException(e);
		}
	}

	/**
	 * 对字符串进行DES加密，返回BASE64编码的加密字符串
	 * 
	 * @param str
	 * @return
	 */
	public static String getEncryptString(String str) {
		Base64 base64en = new Base64();

		try {
			byte[] strBytes = str.getBytes();
			Cipher cipher = Cipher.getInstance("DES");
			cipher.init(Cipher.ENCRYPT_MODE, key);
			byte[] encryptStrBytes = cipher.doFinal(strBytes);
			return base64en.encodeBase64String(encryptStrBytes);
		} catch (Exception ex) {
			ex.printStackTrace();
			return null;
		}
	}

	/**
	 * 对BASE64编码的加密字符串进行解密，返回解密后的字符串
	 * @param str
	 * @return
	 */
	public static String getDecryptString(String str) {
		Base64 base64de = new Base64();

		try {
			byte[] strBytes = base64de.decode(str);
			Cipher cipher = Cipher.getInstance("DES");
			cipher.init(Cipher.DECRYPT_MODE, key);
			byte[] decryptStrBytes = cipher.doFinal(strBytes);
			return new String(decryptStrBytes, "UTF8");
		} catch (Exception e) {
			e.printStackTrace();
		}
		return null;
	}

	public static void main(String[] args) {
		String str = "world";
		String encryptStr = getEncryptString(str);
		String descryptStr = getDecryptString(encryptStr);
		
		System.out.println("encryptStr:"+encryptStr);
		System.out.println("descryptStr:"+descryptStr);
	}
}
